#include "mainwindow.h"

#include <stdio.h>

#define MAX_BTN_COUNT   3
#define BTN_POS_Y       400
#define BTN_WIDTH       120
#define BTN_HEIGHT       50
#define BTN_POS_int     50
#define BTN_PIXELS      18
#define HINT_WIDTH      400
#define HINT_HEIGHT     50
#define HINT_POS_X      ((800-HINT_WIDTH)/2)
#define HINT_POS_Y      350
#define HINT_FONT_PIXELS 20

static ypic *bp = NULL;
static GraphRect btns[MAX_BTN_COUNT];
// static bool isInit = false;

static void __draw_btns();
static void __draw_hint(bool isHint);

// 初始化主界面
void init_mainwindow()
{
    // 读取主界面的图片
    bp = readBmp("../sysimages/main.bmp");
    if (bp == NULL){
        fprintf(stderr, "ypic bp == NULL file:%s %d\n", __FILE__, __LINE__);
    }
}

// 绘制 主界面
void draw_mainwindow(bool isHint)
{
    // 绘制主界面
    draw_graph(bp->data, 0, 0, bp->width, bp->height, bp->bytesPixel, true);

    // 绘制按钮
    __draw_btns();

    // 绘制提示信息
    __draw_hint(isHint);
}

// 检查是否在任一个按钮范围内
int8_t check_MW(int x, int y)
{
    for (int i=0; i<MAX_BTN_COUNT; ++i){
        if ((btns[i].x <= x && btns[i].x+btns[i].width >= x) && (btns[i].y <= y && btns[i].y+btns[i].height >= y)){
            return i;
        }
    }
    return -1;
}

// 销毁主界面
void destroy_mainwindow()
{
    destory_ypic(bp);
}

static void __draw_btns()
{
    // 读取字体文件
    font *fp = fontLoad("../font/simfang.ttf");

        //  检索按钮
    btns[0] = create_Btn(BTN_POS_int, BTN_POS_Y, BTN_WIDTH, BTN_HEIGHT, fp, BTN_PIXELS, 0xffffff, 0x0, "检索");

        // 浏览按钮
    btns[1] = create_Btn(BTN_POS_int*2+BTN_WIDTH, BTN_POS_Y, BTN_WIDTH, BTN_HEIGHT, fp, BTN_PIXELS, 0xffffff, 0x0, "图片浏览");

        // 退出
    btns[2] = create_Btn(BTN_POS_int*3+BTN_WIDTH*2, BTN_POS_Y, BTN_WIDTH, BTN_HEIGHT, fp, BTN_PIXELS, 0xffffff, 0x0, "退出");

    fontUnload(fp);
}

static void __draw_hint(bool isHint)
{
    if (!isHint) return ;
    // 读取字体文件
    font *fp = fontLoad("../font/simfang.ttf");

    bitmap *bmap = createBitmapWithInit(HINT_WIDTH, HINT_HEIGHT, 3, 0xffffff<<8);
    fontSetSize(fp, HINT_FONT_PIXELS);
    fontPrint(fp, bmap, 0, 0, "在浏览图片前请先检索", 0xff0000<<8, 0);
    draw_graph(bmap->map, HINT_POS_X, HINT_POS_Y, bmap->width, bmap->height, bmap->byteperpixel, false);

    fontUnload(fp);
}